#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#

from app import db


########    防火墙  #######
# 外网地址
class Outmap(db.Model):
    __tablename__ = 'fw_outmaps'
    id = db.Column(db.Integer, primary_key=True)
    address = db.Column(db.String(15), unique=True,nullable=False)
    addmap = db.relationship('Fwmapp', backref='outmap')
    position_id = db.Column(db.Integer, db.ForeignKey('fw_positions.id'))

    def __str__(self):
        return '{}'.format(self.outaddress)


# 内网地址
class Inmap(db.Model):
    __tablename__ = 'fw_inmaps'
    id = db.Column(db.Integer, primary_key=True)
    address = db.Column(db.String(15), unique=True, nullable=False)
    addmap = db.relationship('Fwmapp', backref='inmap')
    position_id = db.Column(db.Integer, db.ForeignKey('fw_positions.id'))

    def __str__(self):
        return '{}'.format(self.inaddress)

# 机房位置
class Position(db.Model):
    __tablename__ = "fw_positions"
    id = db.Column(db.Integer, primary_key=True)
    position = db.Column(db.String(30),unique=True)  # 机房位置
    maps = db.relationship('Fwmapp', backref="position", lazy='dynamic')
    inmaps = db.relationship('Inmap', backref="inposition", lazy='dynamic')
    outmaps = db.relationship('Outmap', backref="outposition", lazy='dynamic')


class Fwmapp(db.Model):
    __tablename__ = 'fw_firewalld'
    id = db.Column(db.Integer, primary_key=True)
    protocols = db.Column(db.String(10), unique=False)
    inaddress = db.Column(db.Integer, db.ForeignKey('fw_inmaps.id'))
    inport = db.Column(db.Integer, unique=False)  # 端口可以不唯一
    outaddress = db.Column(db.Integer, db.ForeignKey('fw_outmaps.id'))
    outport = db.Column(db.Integer, unique=False, nullable=False)  # 端口可以不唯一
    serialnumber = db.Column(db.Integer, unique=True)  # 都必须是唯一的
    sequenceid = db.Column(db.Integer, unique=True)  # 都必须是唯一的
    position_id = db.Column(db.Integer, db.ForeignKey('fw_positions.id'))


    def to_json(self):
        dict = self.__dict__
        if "_sa_instance_state" in dict:
            del dict["_sa_instance_state"]
        # if "inaddress_id" in dict:  # 获取fwmapp的 地址 ID号
        #     dict['inaddress_id'] = Inmap.query.filter_by(id=dict['inaddress_id']).first().address
        # if "outaddress_id" in dict:
        #     dict['outaddress_id'] = Outmap.query.filter_by(id=dict['outaddress_id']).first().address
        return dict

    def to_add_json(self):
        dict = self.__dict__
        if "_sa_instance_state" in dict:
            del dict["_sa_instance_state"]
        if "inaddress" in dict:  # 获取fwmapp的 地址 ID号
            dict['inaddress'] = Inmap.query.filter_by(id=dict['inaddress']).first().address
        if "outaddress" in dict:
            dict['outaddress'] = Outmap.query.filter_by(id=dict['outaddress']).first().address
        if "position_id" in dict:
            dict["position_id"] = Position.query.filter_by(id=dict["position_id"]).first().position
        return dict
